#fastapi写的用户登录，原理是用户输入用户名密码后，保存在浏览器cookie中，其他网页先调用本地的cookie，如果存在则跳过正常使用，不存在就跳转到login页面
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
from fastapi import FastAPI, Request, Response
from starlette.responses import HTMLResponse
from fastapi import FastAPI, Form, HTTPException
from starlette.responses import RedirectResponse
from fastapi import FastAPI, Response, status



#用户名密码数据库
fake_users_db = {
    "johndoe": "password123",
    "janedoe": "password456",
    "admin":"000000",
}

app = FastAPI()

#首页，如果有cookie,那么跳转到正式网页， 如果检测到没有cookie,跳转到login
@app.get("/")
def default(request: Request):
    #cookie_value = request.cookies.get("cookie_name")
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')


    return 'hello111'


#简单的login的页面，username, password会以post方式回传给login路由

loginhtml='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form action="/login" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" autocomplete="off" required>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" autocomplete="off" required>
        <button type="submit">Login</button>
    </form>
</body>
</html>
'''


#调用login的html页面
@app.get("/login")
def login(request: Request):
    cookie_value = request.cookies.get("cookie_name")

    return  HTMLResponse(content=loginhtml)


#网页上回传的用户名密码，由下面的post路由处理，判断用户名密码正确后，跳转到set-cookie 设置客户端的cookie,加status_code=303，是为了把post的Redirect转成get
@app.post("/login")
def login_post(request: Request, username: str = Form(...), password: str = Form(...)):
    print(username,password)
    user_password = fake_users_db.get(username)
    if user_password and user_password == password:
        print('yes',username,password,'correct')
    
        #return  RedirectResponse(url='/set-cookie/{}'.format(username),status_code=303)
        return  RedirectResponse(url='/set-cookie/{}'.format(username))



##@app.get("/set-cookie/{name}")
##def set_cookie(response: Response,name:str):
##    print('******************')
##
##    response.set_cookie(key="cookie_name", value=name, path="/")
##    
##    response.status_code = status.HTTP_301_MOVED_PERMANENTLY
##    response.headers["Location"] = "/"
##    return response

#拿到用户名后，写入客户端的cookie中，完成后，跳转回首页
@app.post("/set-cookie/{name}")
def set_cookie_post(response: Response,name:str):
    print('%%%%%%%%%%%%%%%%%%')
    response.set_cookie(key="cookie_name", value=name)
    
    response.status_code = status.HTTP_301_MOVED_PERMANENTLY
    response.headers["Location"] = "/"
    return response





#检查客户端cookie的网页
@app.get("/get-cookie")
def get_cookie(request: Request):
    cookie_value = request.cookies.get("cookie_name")
    if cookie_value:
        return {"cookie_value": cookie_value}
    else:
        return {"message": "Cookie not found"}


if __name__ == "__main__":

    import uvicorn
    #指定fastapi的运行端口
    uvicorn.run(app, host="0.0.0.0",port=80,log_level="info")
